const md5 = require('md5.js');
/**
 * 环境信息
 */
const env = {
  
  // apiUrlPrefix:"http://dev.api.minretail.com"  //测试
  apiUrlPrefix:"https://api.minretail.com"  //正式
}

/**
 * 授权信息
 */
const auth = {
  appId: "sr839eb65082124124" ,
  secret:"839eb6508212412492dc2f0de435c276"
};


/**
 * post请求
 * showLoading:true 显示loading，如果要自定义title使用LoadingTitle;自定义mask使用loadingMask
 * showErrorMessage：true 显示错误提示，否则不显示
 * url:格式：/servicename/methodname  如：/test/get
 * data:参数信息
 * success：成功回调，数据只返回后台数据，不需要wx的包装信息
 * fail:失败回调
 * complete:请求完成提交
 */
const post = options => {
  if (options.showErrorMessage == undefined) options.showErrorMessage = true;
  showLoading(options);
  if (options.url[0] != "/") options.url = "/" + options.url; // 如果开发人员忘记写了，默认加上
  var timestamp = getTimestamp();
  var signString = getSignString(options.url, timestamp);
  if(typeof options.data == 'object' && options.data.constructor != Array) {
    options.data.v = wx.appVersion;
  }
  
  wx.request({
    header: {
      appid: auth.appId,
      timestamp: timestamp,
      signtype: "md5",
      sign: signString
    },
    method: "POST",
    url: env.apiUrlPrefix + options.url,
    data: options.data,
    success: function (res) {
      //console.log(res)
      if (!options.success) return;
      if (!res) return;
      if (res.data.Code == 1) {

      } else if (options.showErrorMessage) {
        var  Res =  res.data;
        if( !options.showErrorMessageJudgetext || options.showErrorMessageJudgetext  != Res.Message) {
          wx.showModal({
            content: res.data.Message ? res.data.Message : "errcode:" + res.data.Code,
            showCancel: false,
            confirmText: "我知道了",
            success (res) {
              if (res.confirm) {
                options.showErrorMessageConfirm && options.showErrorMessageConfirm(Res);
              } else if (res.cancel) {
                options.showErrorMessageCancel && options.showErrorMessageCancel(Res);
              }
            }
          });
        }else {
          options.showErrorMessageConfirm && options.showErrorMessageConfirm(Res);
        }
        

       
        var currentPage =  getCurrentPages()[getCurrentPages().length - 1].route;
        var debugInfo = (res.data.Message ? res.data.Message : "errcode:" + res.data.Code) + '||' + currentPage + '||'+  options.url  + '||' + JSON.stringify(options.data);
        console.log(debugInfo);

      }
      options.success(res.data); // 只返回后台数据，不需要wx的包装信息
    },
    fail: function (err) {
      if (!options.fail) return;
      options.fail(err);
      
      
      var currentPage =  getCurrentPages()[getCurrentPages().length - 1].route;
     // var debugInfo = (res.data.Message ? res.data.Message : "errcode:" + res.data.Code)  + '||' + currentPage + '||'+ options.url  + '||' + JSON.stringify(options.data);
      //console.log(debugInfo);
    },
    complete: function (res) {
      if (options.showLoading == undefined || options.showLoading) {
        wx.hideLoading();
        wx.hideNavigationBarLoading({
          complete: (res) => {},
        });
      }
      if (!options.complete) return;
      options.complete(res);
    },
  });
}
/**
 * post请求Loading
 */
const showLoading = options => {
  if (options.showLoading == undefined) options.showLoading = true;
  if (!options.showLoading) return;
  if (!options.loadingTitle) {
    wx.showNavigationBarLoading({
      complete: (res) => {},
    })
  } else {
    wx.showLoading({
      title: options.loadingTitle ? options.loadingTitle : "加载中...",
      mask: options.loadingMask ? options.loadingMask : false,
    });
  }
}

/**
 * 上传文件
 * showLoading:true 显示loading，如果要自定义title使用LoadingTitle;自定义mask使用loadingMask
 * showErrorMessage：true 显示错误提示，否则不显示
 * url:格式：/servicename/methodname  如：/test/get
 * filePath:本地文件路径
 * name:文件名称
 * formData:表单数据
 * success：成功回调，数据只返回后台数据，不需要wx的包装信息
 * fail:失败回调
 * complete:请求完成提交
 */
const upload = options => {
  if (options.showErrorMessage == undefined) options.showErrorMessage = true;
  showLoading(options);
  var timestamp = getTimestamp();
  var signString = getSignString(options.url, timestamp);
  if (options.url[0] != "/") options.url = "/" + options.url; // 如果开发人员忘记写了，默认加上
  wx.uploadFile({
    header: {
      appid: auth.appId,
      timestamp: timestamp,
      signtype: "md5",
      sign: signString,
      "Content-Type": "multipart/form-data"
    },
    url: env.apiUrlPrefix + options.url,
    filePath: options.filePath,
    name: options.name ? options.name : "file",
    formData: options.formData ? options.formData : {},
    success: function (res) {
      //console.log(res)
      if (!res) return;
      res.data = JSON.parse(res.data);
      if (res.data.Code == 1) {

      } else if (options.showErrorMessage) {
        wx.showModal({
          content: res.data.Message ? res.data.Message : "errcode:" + res.data.Code,
          showCancel: false,
          confirmText: "我知道了"
        });
      }
      if (options.success) options.success(res.data); // 只返回后台数据，不需要wx的包装信息
    },
    fail: function (err) {
      if (!options.fail) return;
      options.fail(err);
    },
    complete: function (res) {
      if (options.showLoading == undefined || options.showLoading) wx.hideLoading();
      if (!options.complete) return;
      options.complete(res);
    },
  });
};


/**
 * 获取时间戳
 */
const getTimestamp = () => {
  return Math.round(new Date() / 1000).toString();
}

/**
 * 获取签名字符串
 */
const getSignString = (url, timestamp) => {
  if (!url) throw Error("url can't null！！");
  var urlArray = url.split('/');
  var v = [auth.appId, urlArray[1], urlArray[2], timestamp,auth.secret].join(".");
  var md5Val = md5.to_md5( v);
  return md5Val;
}

/**
 * 公开属性与函数
 */
module.exports = {
  post: post,
  upload: upload
}